<template>
  <div class="admin-header-container">
    <!-- 左侧：折叠按钮 -->
    <div class="header-left">
      <el-button
        circle
        @click="$emit('toggle-collapse')"
        class="collapse-btn"
      >
        <el-icon><Expand /></el-icon>
      </el-button>
    </div>

    <!-- 右侧：用户信息和操作 -->
    <div class="header-right">
      <!-- 用户信息 -->
      <el-dropdown>
        <div class="user-info">
          <el-avatar :size="32">{{ adminName ? adminName.charAt(0).toUpperCase() : 'A' }}</el-avatar>
          <span class="user-name">{{ adminName || '管理员' }}</span>
          <el-icon class="el-icon--right"><ArrowDown /></el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>
              <el-icon><User /></el-icon>
              个人信息
            </el-dropdown-item>
            <el-dropdown-item divided @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Expand,
  ArrowDown,
  User,
  SwitchButton
} from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/authStore'

defineEmits(['toggle-collapse'])

const router = useRouter()
const auth = useAuthStore()
const adminName = ref('管理员')

// 获取管理员信息
const getAdminInfo = async () => {
  try {
    const response = await request.get('/admin/auth/info')
    if (response.code === 0 && response.data) {
      adminName.value = response.data.nickName || response.data.username || '管理员'
    }
  } catch (error) {
    console.error('获取管理员信息失败', error)
    // 确保即使请求失败，adminName 也有默认值
    adminName.value = '管理员'
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 使用 authStore 统一清除管理员登录信息
    auth.logoutAdmin()
    ElMessage.success('已退出登录')
    router.push('/admin/login')
  } catch (error) {
    // 用户取消
  }
}

onMounted(() => {
  getAdminInfo()
})
</script>

<style scoped>
.admin-header-container {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.collapse-btn {
  font-size: 20px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 0 12px;
  height: 40px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.user-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}
</style>

